package ai4games_tests.soccer;

import game2dai.World;
import game2dai.entities.BaseEntity;
import game2dai.fsm.Dispatcher;
import game2dai.fsm.State;
import game2dai.fsm.Telegram;

public class PitchPlayersOff extends State implements Constants {


	private static PitchPlayersOff instance = null;	

	public static PitchPlayersOff state(){
		if(instance == null){
			instance = new PitchPlayersOff();
			instance.name = "Players Off";
		}
		return instance;
	}

	@Override
	public void enter(BaseEntity owner) {
		Pitch pitch = (Pitch) owner;
		pitch.ballInPlay = false;
		pitch.playersOffPitch = true;
		pitch.teams[0].sendTeamOffPitch();
		pitch.teams[1].sendTeamOffPitch();
		pitch.ball.toCentreSpot(PITCH_LENGTH/2, PITCH_WIDTH/2);
	}

	@Override
	public void execute(BaseEntity owner, double deltaTime, World world) {
		Pitch pitch = (Pitch) owner;
		if(pitch.teams[0].allPlayersReachedTarget() && pitch.teams[1].allPlayersReachedTarget()){
			// Make sure we only do this once
			pitch.teams[0].nbrReachedTarget = 0;
			pitch.teams[1].nbrReachedTarget = 0;
			
			pitch.ball.toCentreSpot(PITCH_LENGTH/2, PITCH_WIDTH/2);
			// Select 2 new teams for the next match
			pitch.newTeams();
			Dispatcher.dispatch(2000, pitch.ID(), pitch.ID(), TEAMS_PREPARE_FOR_KICK_OFF);
		}
	}

	@Override
	public void exit(BaseEntity owner) {

	}

	@Override
	public boolean onMessage(BaseEntity owner, Telegram tgram) {
		Pitch pitch = (Pitch) owner;
		switch(tgram.msg){
		case TEAMS_PREPARE_FOR_KICK_OFF:
			pitch.FSM().changeState(PitchPrepareForKickOff.state());
			return true;
		}
		return false;
	}

}
